<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="Access-Control-Allow-Origin" content="*" />
	<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1,minimum-scale=1,user-scalable=no">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<script src="js/jquery.js"></script>
	<title>分享您的特权价！</title>
	<style>
		body{
			height: 100%;
			margin:0;
			padding:0;
		}
		#main {
			display:flex;
		}
		#main canvas {width:100%;height:100%;}
		.loader {
			background: #000;
			background: radial-gradient(#222, #000);
			bottom: 0;
			left: 0;
			overflow: hidden;
			position: fixed;
			right: 0;
			top: 0;
			z-index: 99999;
		}
		.loader .loader-tip{
			color:#aaa;
			text-align:center;
			position: absolute;
			width: 100%;
			top:100px;
		}

		.loader-inner {
			bottom: 0;
			height: 60px;
			left: 0;
			margin: auto;
			position: absolute;
			right: 0;
			top: 0;
			width: 100px;
		}

		.loader-line-wrap {
			animation: spin 2000ms cubic-bezier(.175, .885, .32, 1.275) infinite;
			box-sizing: border-box;
			height: 50px;
			left: 0;
			overflow: hidden;
			position: absolute;
			top: 0;
			transform-origin: 50% 100%;
			width: 100px;
		}
		.loader-line {
			border: 4px solid transparent;
			border-radius: 100%;
			box-sizing: border-box;
			height: 100px;
			left: 0;
			margin: 0 auto;
			position: absolute;
			right: 0;
			top: 0;
			width: 100px;
		}
		.loader-line-wrap:nth-child(1) { animation-delay: -50ms; }
		.loader-line-wrap:nth-child(2) { animation-delay: -100ms; }
		.loader-line-wrap:nth-child(3) { animation-delay: -150ms; }
		.loader-line-wrap:nth-child(4) { animation-delay: -200ms; }
		.loader-line-wrap:nth-child(5) { animation-delay: -250ms; }

		.loader-line-wrap:nth-child(1) .loader-line {
			border-color: hsl(0, 80%, 60%);
			height: 90px;
			width: 90px;
			top: 7px;
		}
		.loader-line-wrap:nth-child(2) .loader-line {
			border-color: hsl(60, 80%, 60%);
			height: 76px;
			width: 76px;
			top: 14px;
		}
		.loader-line-wrap:nth-child(3) .loader-line {
			border-color: hsl(120, 80%, 60%);
			height: 62px;
			width: 62px;
			top: 21px;
		}
		.loader-line-wrap:nth-child(4) .loader-line {
			border-color: hsl(180, 80%, 60%);
			height: 48px;
			width: 48px;
			top: 28px;
		}
		.loader-line-wrap:nth-child(5) .loader-line {
			border-color: hsl(240, 80%, 60%);
			height: 34px;
			width: 34px;
			top: 35px;
		}

		@keyframes spin {
			0%, 15% {
				transform: rotate(0);
			}
			100% {
				transform: rotate(360deg);
			}
		}
	</style>
</head>

<body>
	<div id="main"><canvas id="myCanvas" width="1080" height="1620">当前浏览器版本过低，请使用其他浏览器尝试</canvas></div>
	<div style="display:none"><canvas id="tmpCanvas" width="1080" height="1620"></canvas></div> <!-- style="display:none" -->
	<div class="loader">
		<div class="loader-tip">正在生成商品海报</div>
		<div class="loader-inner">
			<div class="loader-line-wrap">
				<div class="loader-line"></div>
			</div>
			<div class="loader-line-wrap">
				<div class="loader-line"></div>
			</div>
			<div class="loader-line-wrap">
				<div class="loader-line"></div>
			</div>
			<div class="loader-line-wrap">
				<div class="loader-line"></div>
			</div>
			<div class="loader-line-wrap">
				<div class="loader-line"></div>
			</div>
		</div>
	</div>

	<script type="text/javascript">
        //防止token变更
        document.cookie.split(" ").join("").split(";").forEach(function(cookie){
            if(cookie.indexOf("token")==0){
                let hostname = window.location.hostname.substring(window.location.hostname.indexOf("."));
                let token = cookie.split("=")[1];
                let fn = function(){
                    document.cookie = "token="+ escape (token) + ";domain="+hostname+";path=/";
                };
                document.addEventListener("mousedown",fn);
                document.addEventListener("touchstart",fn);
                document.addEventListener("click",fn);
            }
        });
		var apiHost = "https://"+window.location.hostname+"/plugin/api";
		var key='haibao.setting.rate';
		function GetQueryString(name) {
			 var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
			 var r = window.location.search.substr(1).match(reg);
			 if(r!=null)return  unescape(r[2]); return null;
		}
		//自动换行文字
		CanvasRenderingContext2D.prototype.wrapText = function (text, x, y, maxWidth, lineHeight) {
			if (typeof text != 'string' || typeof x != 'number' || typeof y != 'number') {
				return;
			}
			
			var context = this;
			var canvas = context.canvas;
			
			if (typeof maxWidth == 'undefined') {
				maxWidth = (canvas && canvas.width) || 300;
			}
			if (typeof lineHeight == 'undefined') {
				lineHeight = (canvas && parseInt(window.getComputedStyle(canvas).lineHeight)) || parseInt(window.getComputedStyle(document.body).lineHeight);
			}
			
			// 字符分隔为数组
			var arrText = text.split('');
			var line = '';
			
			for (var n = 0; n < arrText.length; n++) {
				var testLine = line + arrText[n];
				var metrics = context.measureText(testLine);
				var testWidth = metrics.width;
				if (testWidth > maxWidth && n > 0) {
					context.fillText(line, x, y);
					line = arrText[n];
					y += lineHeight;
				} else {
					line = testLine;
				}
			}
			context.fillText(line, x, y);
		};
		//裁剪圆形图片
		CanvasRenderingContext2D.prototype.circleImg = function (img, x, y, r) {
			this.save();
			var d =2 * r;
			var cx = x + r;
			var cy = y + r;
			this.arc(cx, cy, r, 0, 2 * Math.PI);
			this.clip();
			this.drawImage(img, x, y, d, d);
			this.restore();
		};
		var tryCount = 0;
		var drawing = false,loader = 5;
		var prdImage = new Image(),qrImage = new Image(),accountImage = new Image(),prdName,prdMoney=0,appName,accountName,rate=0;
		var canvas = document.getElementById('myCanvas');
		var ctx = canvas.getContext("2d");
		var tmpCanvas = document.getElementById('tmpCanvas');
		var tmpCtx = tmpCanvas.getContext("2d");
		$.ajaxSetup({crossDomain: true, xhrFields: {withCredentials: true}});
		prdImage.name = "商品图片";
		qrImage.name = "二维码图片";
		accountImage.name = "用户头像";
		function createImage() {
			if(loader>0 || drawing) return;	//所有信息都载入完成再生成海报
			drawing = true;
			var metrics,tmpWidth,tmpLeft,text;
			//画背景
			ctx.rect(0 , 0 , canvas.width , canvas.height);
			ctx.fillStyle = "#fff";
			ctx.fill();

			//用户头像 +向你推荐
			tmpLeft = 0;
			tmpCanvas.width = tmpCanvas.width;	//清空画布
			if(accountImage.complete) {
				tmpCtx.circleImg(accountImage,0,0,50);
				//tmpCtx.drawImage(accountImage,0,0,60,60);
				tmpLeft = 120;
			}
			tmpCtx.fillStyle = "#000";
			tmpCtx.textAlign = 'left';//设置文本的水平对齐方式
			tmpCtx.textBaseline = 'middle'; //设置文本的垂直对齐方式
			tmpCtx.font="40px Verdana";
			tmpCtx.fillText(accountName, tmpLeft , 25);
			metrics = tmpCtx.measureText(accountName);
			tmpWidth = metrics.width + tmpLeft;
			
			tmpCtx.fillStyle = "#999";
			tmpCtx.font="35px Verdana";
			text = "向你推荐";
			tmpCtx.fillText(text, tmpLeft + 5 , 75);
			
			metrics = tmpCtx.measureText(text);
			tmpWidth = Math.max(metrics.width + tmpLeft + 5,tmpWidth);
			
			ctx.drawImage(tmpCanvas, 0, 0, tmpWidth ,100,(canvas.width-tmpWidth)/2,20,tmpWidth,100);

			//商品图片 自动缩放
			var maxWidth = canvas.width - 100;
			var maxHeight = canvas.width - 100;
			var tmpS = Math.max(prdImage.width/maxWidth,prdImage.height/maxHeight);
			var dWidth = prdImage.width / tmpS;
			var dHeight = prdImage.height / tmpS;
			ctx.drawImage(prdImage,0,0,prdImage.width,prdImage.height,(canvas.width-dWidth)/2, 100 + 50 + (maxHeight - dHeight)/2, dWidth,dHeight);
			
			//二维码 300x300
			tmpCanvas.width = tmpCanvas.width;
			tmpCtx.drawImage(qrImage,10,10,280,280);
			tmpCtx.strokeStyle = "#f00";
			tmpCtx.lineWidth = 3; //设置线宽
			tmpCtx.beginPath();
			tmpCtx.moveTo(1, 1);
			tmpCtx.lineTo(1, 30);
			tmpCtx.moveTo(1, 1);
			tmpCtx.lineTo(30, 1);
			tmpCtx.moveTo(299, 0);
			tmpCtx.lineTo(299, 30);
			tmpCtx.moveTo(299, 0);
			tmpCtx.lineTo(269, 0);
			tmpCtx.moveTo(1, 299);
			tmpCtx.lineTo(1, 269);
			tmpCtx.moveTo(1, 299);
			tmpCtx.lineTo(30, 299);
			tmpCtx.moveTo(299, 299);
			tmpCtx.lineTo(299, 269);
			tmpCtx.moveTo(299, 299);
			tmpCtx.lineTo(269, 299);
			tmpCtx.stroke();
			tmpCtx.closePath();
			ctx.drawImage(tmpCanvas,0,0,300,300,755,canvas.width + 100,300,300);
			
			ctx.fillStyle = "#f00";
			ctx.textAlign = 'center';
			ctx.textBaseline = 'top';
			ctx.font="20px Verdana";
			ctx.fillText("扫描或长按二维码", 755+150,canvas.width + 85, 240);

			//商品名称
			ctx.fillStyle = "#000";
			ctx.textAlign = 'left';
			ctx.textBaseline = 'top';
			ctx.font="40px Verdana";
			ctx.wrapText(prdName, 50, canvas.width + 120, canvas.width - 400 - 50, 40);
			
			//商品价格
			ctx.textBaseline = 'middle'; //设置文本的垂直对齐方式
			if(rate && rate > 0 ) {
				ctx.font="50px Verdana";
				ctx.fillStyle = "#ff0000";
				text = "特权价：￥" + (prdMoney*rate).toFixed(2)
				ctx.fillText(text, 50 , canvas.width + 300);
				
				ctx.fillStyle = "#999";
				ctx.font="35px Verdana";
				text = "原价：￥" + prdMoney.toFixed(2);
				ctx.fillText(text, 50 , canvas.width + 360);
				metrics = ctx.measureText(text);
				tmpWidth = Math.max(metrics.width+50,tmpWidth);
				ctx.fillStyle = "#ff0";
				ctx.beginPath();
				ctx.moveTo(50, canvas.width + 360);
				ctx.lineTo(50 + metrics.width, canvas.width + 360);
				ctx.stroke();
			} else {
				ctx.font="50px Verdana";
				text = "价格：￥" + prdMoney.toFixed(2)
				ctx.fillText(text, 50 , canvas.width + 360);
			}

			//商铺名称
			ctx.fillStyle = "#333";
			ctx.textAlign = 'center';//设置文本的水平对齐方式
			ctx.textBaseline = 'middle'; //设置文本的垂直对齐方式
			ctx.font="40px Verdana";
			ctx.fillText(appName, canvas.width /2 , canvas.width + 450 , canvas.width - 60);

			ctx.textAlign = 'center';//设置文本的水平对齐方式
			ctx.fillStyle = "#aaa";
			ctx.font="30px Verdana";
			ctx.fillText("长按图片进行分享转发", canvas.width / 2 , canvas.width + 510 , canvas.width - 50);
			
			/*//TODO START
			$('.loader').fadeOut();
			drawing = false;
			return;
			//TODO END*/
			
			//预览图片
			var code = canvas.toDataURL("image/jpeg",0.8);
			var parts = code.split(';base64,');
            /*
			$.post(apiHost+"/image.base64.to.png",{code:parts[1]},function(res){
				$.ajax({
					url:apiHost+"/wx.app.call?name=previewImage",
					type:"POST",
					data:JSON.stringify({current:res}),
					contentType:"application/json; charset=utf-8",
					dataType:"json",
					complete: function(){
						$('.loader').fadeOut();
						drawing = false;
					},
				});
			});
            */
            $.ajax({
                url:apiHost+"/image.base64.to.png",
                type:"POST",
                data:parts[1],
                contentType:"text/plain",
                success: function(res){
                    var open = function(){
                        $.ajax({
                            url:apiHost+"/wx.app.call?name=previewImage",
                            type:"POST",
                            data:JSON.stringify({current:res,urls:[res]}),
                            contentType:"application/json; charset=utf-8",
                            dataType:"json",
                            complete: function(){
                                $('.loader').fadeOut();
                                drawing = false;
                            },
                        });
                    }
                    open();
                    $("#main").click(open);
                },
            });
		}
        function base64Decode(input) {  
            var output = "";  
            var chr1, chr2, chr3;  
            var enc1, enc2, enc3, enc4;  
            var i = 0;  
            input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");  
            while (i < input.length) {  
                enc1 = _keyStr.indexOf(input.charAt(i++));  
                enc2 = _keyStr.indexOf(input.charAt(i++));  
                enc3 = _keyStr.indexOf(input.charAt(i++));  
                enc4 = _keyStr.indexOf(input.charAt(i++));  
                chr1 = (enc1 << 2) | (enc2 >> 4);  
                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);  
                chr3 = ((enc3 & 3) << 6) | enc4;  
                output = output + String.fromCharCode(chr1);  
                if (enc3 != 64) {  
                    output = output + String.fromCharCode(chr2);  
                }  
                if (enc4 != 64) {  
                    output = output + String.fromCharCode(chr3);  
                }  
            }  
            output = _utf8_decode(output);  
            return output;  
        }
		function base64Encode(str) {
			var CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
			var out = "", i = 0, len = str.length, c1, c2, c3;
			while (i < len) {
				c1 = str.charCodeAt(i++) & 0xff;
				if (i == len) {
					out += CHARS.charAt(c1 >> 2);
					out += CHARS.charAt((c1 & 0x3) << 4);
					out += "==";
					break;
				}
				c2 = str.charCodeAt(i++);
				if (i == len) {
					out += CHARS.charAt(c1 >> 2);
					out += CHARS.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
					out += CHARS.charAt((c2 & 0xF) << 2);
					out += "=";
					break;
				}
				c3 = str.charCodeAt(i++);
				out += CHARS.charAt(c1 >> 2);
				out += CHARS.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
				out += CHARS.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
				out += CHARS.charAt(c3 & 0x3F);
			}
			return out;
		}
		function LoadSuccess() {
			loader--;
			createImage();
		}
		function LoadFail(msg) {
			var html = $('.loader-tip').html();
			$('.loader-tip').html('载入' + (!msg?this.name:msg) + '失败');
		}
		function ImageLoader(img,src) {
			img.setAttribute("crossOrigin",'Anonymous');
			img.onload = LoadSuccess;
			img.onerror = LoadFail;
			img.src = src;
		}

		var app_id = GetQueryString("app_id");
		var product_id = GetQueryString("product_id");
		function start() {
			loader = 5;
			//店铺名称
			$.get(apiHost+"/app.get?app_id="+app_id).done(function(res){
				appName = res.result.app_name;
				LoadSuccess();
			}).fail(function(){LoadFail('店铺信息')});
			
			//商品信息
			$.get(apiHost+"/product.get?app_id="+app_id+"&product_id="+product_id).done(function(res){
				prdName = res.result.name;
				prdMoney = res.result.salemoney;
				ImageLoader(prdImage,res.result.album[0]+"?imageView2/5/w/600/h/600");
			}).fail(function(){LoadFail('商品信息')});
			
			//用户信息
			$.get(apiHost+"/account.get.current").done(function(res){
				accountName = res.result.nick_name;
				ImageLoader(accountImage,res.result.avatar_url);
                //优惠信息
                $.ajax({
                    url:apiHost+"/cache.app.get?app_id="+app_id+"&key="+key,
                    type:"POST",
                    contentType:"application/json; charset=utf-8",
                    dataType:"json"
                }).done(function(res){
                    if(res && res.privilege && res.rate > 0){
                        rate = res.rate;
                    }
                }).then(function(){
                    LoadSuccess();
                    //二维码
                    var conf;
                    if(rate && rate > 0 ) {
                        conf={action:"openShareItem",productId:product_id,rate:rate,accountId:res.result.id};
                    } else {
                        conf={action:"openShareItem",productId:product_id,accountId:res.result.id};
                    }
                    $.ajax({
                        url:apiHost+'/wx.app.qrcode.shop.launch?app_id='+app_id+'&width=180',
                        type:"POST",
                        data:{scene:JSON.stringify(conf)},
                        mimeType: "text/plain; charset=x-user-defined"
                    }).done(function(res) {
                        ImageLoader(qrImage,'data:image/png;base64,'+base64Encode(res));
                    }).fail(function(){
                        LoadFail('二维码信息');
                    });
                });
			}).fail(function(){LoadFail('用户信息')});

			
		}
		start();
		/*
		appName = "测试店铺123";
		callback();
		
		rate = 0.8;
		callback();
		
		prdName = "测试商品测试商品测试商品测试商品";
		prdMoney = 1000;
		ImageLoader(prdImage,"images/prd.png");
		
		accountName = "测试用户测试用户测试用户测试用户";
		ImageLoader(accountImage,"images/account.jpg");
		
		ImageLoader(qrImage,"images/qr.png");
		*/

	</script>
</body>

</html>